package com.msconfig.mvp.view.fragment;

/*
 * author: caojunhao
 * date  : 2020/6/17
 * desc  :
 */

import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.geo.msconfig.R;
import com.msconfig.bean.ConfigFileDetailBean;
import com.msconfig.bean.deviceInfoBean.TagDeviceInfo;
import com.msconfig.device.CommandParseManage;
import com.msconfig.device.CommandSendManage;
import com.msconfig.device.GetSendCommandList;
import com.msconfig.device.TagSendCommand;
import com.msconfig.event.NullEvent;
import com.msconfig.mvp.view.activity.base.BaseMvpFragment;
import com.msconfig.mvp.view.activity.base.BasePresenter;
import com.msconfig.mvp.view.adapter.ConfigFileDetailAdapter;
import com.msconfig.utils.BaseConversionUtil;
import com.msconfig.utils.SpUtils;
import com.msconfig.widget.MyListView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static android.view.View.VISIBLE;
import static com.msconfig.mvp.view.fragment.ApplyConfigFragment.FILENAME;

public class ConfigFileDetailFragment extends BaseMvpFragment implements View.OnClickListener {
    private ImageView ivCommonBack;
    private TextView tvCommonTitle;
    private MyListView myListView;
    private ConfigFileDetailAdapter adapter;
    private ArrayList<ConfigFileDetailBean> configFileDetailBeans;
    private String fileName;
    private TagDeviceInfo deviceInfo;
    private CommandParseManage mCommandParseManage = CommandParseManage.getInstance();
    protected static final int MSG_READ_SUCC =1;
    private MyHandler myHandler;
    private String title;
    private String content;
    private ConfigFileDetailBean configFileDetailBean;


    private static class MyHandler extends Handler {

        WeakReference<ConfigFileDetailFragment> weakReference;

        private MyHandler(ConfigFileDetailFragment fragment) {
            weakReference = new WeakReference<ConfigFileDetailFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            ConfigFileDetailFragment fragment = weakReference.get();
            if (fragment != null) {
                switch (msg.what) {
                    case MSG_READ_SUCC:
                        fragment.showProcessData();
                        //因为前面解析是使用了解析库，把deviceInfo.gprsInfo里面的数据都变成了现在文件中的数据，主机的数据自然就不对
                        //因此需要在获取一边GETALL得到当前主机的信息
                        ArrayList<TagSendCommand> sendCommandList= GetSendCommandList.getGetAllCommandList();
                        //设置发送命令额集合
                        CommandSendManage.getInstance().setSendCommandList(sendCommandList);
                        //开始发送命令
                        CommandSendManage.getInstance().startSendCommand();
                        break;
                }
            }
        }
    }

    private void showProcessData() {
        showGprsData();
        showWifiData();
        showSurVeyData();
        showTranformData();

        adapter.notifyDataSetChanged();
    }

    private void showTranformData() {
        title="启用输出";
        String projectionMode = "";
        if(deviceInfo.transformInfo.mStartOutput){
            content="启用";
        }else{
            content="未启用";
        }
        addToConfigFileDetailBeans(title,content);

        title="椭球名称";
        content=deviceInfo.transformInfo.mEllipsoidName;
        addToConfigFileDetailBeans(title,content);

        title="长半轴(a)";
        content=deviceInfo.transformInfo.mEllipsoidLongHalfshaft;
        addToConfigFileDetailBeans(title,content);

        title="扁率倒数(1/f)";
        content=deviceInfo.transformInfo.mEllipsoidFlatteningInverse;
        addToConfigFileDetailBeans(title,content);

        String mProjectionMode=deviceInfo.transformInfo.mProjectionMode;
        switch (Integer.parseInt(mProjectionMode)){
            case 0:
                projectionMode=getString(R.string.gauss_projection);
                break;
            case 1:
                projectionMode=getString(R.string.utm_projection);
                title="投影方式";
                content=projectionMode;
                addToConfigFileDetailBeans(title,content);

                title="中央经线";
                content=String.valueOf(((Double.parseDouble(deviceInfo.transformInfo.mCentralMeridian)*180)/Math.PI));
                addToConfigFileDetailBeans(title,content);
                return;
            case 2:
                projectionMode=getString(R.string.transverse_mercator_projection);
                break;
            case 3:
                projectionMode=getString(R.string.oblique_stereographic_projection);
                break;
            case 4:
                projectionMode=getString(R.string.double_stereographic_projection);
                break;
        }
        title="投影方式";
        content=projectionMode;
        addToConfigFileDetailBeans(title,content);

        title="中央经线";
        content=String.valueOf(((Double.parseDouble(deviceInfo.transformInfo.mCentralMeridian)*180)/Math.PI));
        addToConfigFileDetailBeans(title,content);

        title="北加常数";
        content=deviceInfo.transformInfo.mNorgaConstant;
        addToConfigFileDetailBeans(title,content);

        title="东加常数";
        content=deviceInfo.transformInfo.mEastgaConstant;
        addToConfigFileDetailBeans(title,content);

        title="投影比例尺";
        content=deviceInfo.transformInfo.mProjectionScale;
        addToConfigFileDetailBeans(title,content);

        title="投影高";
        content=deviceInfo.transformInfo.mProjectionHeight;
        addToConfigFileDetailBeans(title,content);

        title="基准纬度";
        content=deviceInfo.transformInfo.mBaseLatitude;
        addToConfigFileDetailBeans(title,content);

        if(deviceInfo.transformInfo.mIsUseSevenParameter){
            title="七参数";
            content="启用";
            addToConfigFileDetailBeans(title,content);

            title="x平移";
            content=deviceInfo.transformInfo.mSevenXTranslation;
            addToConfigFileDetailBeans(title,content);

            title="y平移";
            content=deviceInfo.transformInfo.mSevenYTranslation;
            addToConfigFileDetailBeans(title,content);

            title="z平移";
            content=deviceInfo.transformInfo.mSevenZTranslation;
            addToConfigFileDetailBeans(title,content);

            title="x旋转";
            content=deviceInfo.transformInfo.mSevenXRotate;
            addToConfigFileDetailBeans(title,content);

            title="y旋转";
            content=deviceInfo.transformInfo.mSevenYRotate;
            addToConfigFileDetailBeans(title,content);

            title="z旋转";
            content=deviceInfo.transformInfo.mSevenZRotate;
            addToConfigFileDetailBeans(title,content);

            title="缩放";
            content=deviceInfo.transformInfo.mSevenScale;
            addToConfigFileDetailBeans(title,content);
        }else{
            title="七参数";
            content="未启用";
            addToConfigFileDetailBeans(title,content);
        }
        if(deviceInfo.transformInfo.ismIsUseFourParameter){
            title="四参数";
            content="启用";
            addToConfigFileDetailBeans(title,content);

            title="x平移";
            content=deviceInfo.transformInfo.mFourXTranslation;
            addToConfigFileDetailBeans(title,content);

            title="y平移";
            content=deviceInfo.transformInfo.mFourYTranslation;
            addToConfigFileDetailBeans(title,content);

            title="旋转";
            content=deviceInfo.transformInfo.mFourRotate;
            addToConfigFileDetailBeans(title,content);

            title="缩放";
            content=deviceInfo.transformInfo.mFourScale;
            addToConfigFileDetailBeans(title,content);
        }else{
            title="四参数";
            content="未启用";
            addToConfigFileDetailBeans(title,content);
        }
    }

    private void showSurVeyData() {
        title="测站名称";
        content=deviceInfo.surveyInfo.mSurveyName;
        addToConfigFileDetailBeans(title,content);

        title="记录间隔";
        content=Integer.parseInt(deviceInfo.surveyInfo.mRecordingInterval)/3600+"小时";
        addToConfigFileDetailBeans(title,content);

        title="数据链";
        if(deviceInfo.surveyInfo.mDataLink.equals("NETWORK")){
            content="网络";
        }else{
            content="电台";
        }
        addToConfigFileDetailBeans(title,content);

        title="第一基站IP";
        content=deviceInfo.surveyInfo.mFirstIp;
        addToConfigFileDetailBeans(title,content);

        title="第一基站端口";
        content=deviceInfo.surveyInfo.mFirstPort;
        addToConfigFileDetailBeans(title,content);

        title="双基站";
        if(deviceInfo.surveyInfo.mIsDoubleStation){
            content="启用";
            addToConfigFileDetailBeans(title,content);

            title="第二基站IP";
            content=deviceInfo.surveyInfo.mSecondIp;
            addToConfigFileDetailBeans(title,content);

            title="第二基站端口";
            content=deviceInfo.surveyInfo.mSecondPort;
            addToConfigFileDetailBeans(title,content);
        }else{
            content="未启用";
            addToConfigFileDetailBeans(title,content);
        }

        title="结果回传IP";
        content=deviceInfo.surveyInfo.mResultIp;
        addToConfigFileDetailBeans(title,content);

        title="结果回传端口";
        content=deviceInfo.surveyInfo.mResultPort;
        addToConfigFileDetailBeans(title,content);

        if(deviceInfo.surveyInfo.mIsStartTiming!=null){
            title="定时开关机";
            if(Integer.parseInt(deviceInfo.surveyInfo.mIsStartTiming)==0){
                content="未启用";
                addToConfigFileDetailBeans(title,content);
            }else{
                content="启用";
                addToConfigFileDetailBeans(title,content);

                String[] values=deviceInfo.surveyInfo.mIsStartTiming.split("\\|");
                String data= BaseConversionUtil.Decimal2Binary(Integer.parseInt(values[0]));
                String name = "";
                //1111111-星期日-》星期一
                for(int i=data.length()-1;i>=0;i--){
                    if(Integer.parseInt(data.substring(i-1,i))==1){//最后一位星期一
                        switch (i){
                            case 6:
                                name="星期一";
                                break;
                            case 5:
                                name="二";
                                break;
                            case 4:
                                name="三";
                                break;
                            case 3:
                                name="四";
                                break;
                            case 2:
                                name="五";
                                break;
                            case 1:
                                name="六";
                                break;
                            case 0:
                                name="日";
                                break;
                        }

                    }
                    name += "、";
                }
                title="开机日期";
                content=name;
                addToConfigFileDetailBeans(title,content);

                title="开机时间";
                content=values[1]+":00";
                addToConfigFileDetailBeans(title,content);

                title="工作时长";
                content=values[2]+"小时";
                addToConfigFileDetailBeans(title,content);

                title="关机电量";
                content=values[3]+"%";
                addToConfigFileDetailBeans(title,content);
            }
        }


        title="外接传感器";
        if(deviceInfo.surveyInfo.mIsExternalSensor){
            content="未启用";
        }else{
            content="启用";
        }
        addToConfigFileDetailBeans(title,content);

        title="地灾物联网平台";
        if(deviceInfo.surveyInfo.mIsEarthDisaster){
            content="未启用";
        }else{
            content="启用";
        }
        addToConfigFileDetailBeans(title,content);

        String type="";
        int communicationSetup= Integer.parseInt(deviceInfo.surveyInfo.mCommunicationSetup);
        switch (communicationSetup){
            case 0:
                type=getString(R.string.close);
                title="通讯设置";
                content=type;
                addToConfigFileDetailBeans(title,content);
                return;
            case 1:
                type=getString(R.string.tcp_client);
                break;
            case 2:
                type=getString(R.string.tcp_server);
                break;
        }
        title="通讯设置";
        content=type;
        addToConfigFileDetailBeans(title,content);

        title="服务器地址";
        content=deviceInfo.surveyInfo.mServerAdress;
        addToConfigFileDetailBeans(title,content);

        title="服务器端口";
        content=deviceInfo.surveyInfo.mServerPort;
        addToConfigFileDetailBeans(title,content);

    }

    private void showWifiData() {
        title="WIFI模式";
        switch (deviceInfo.wifiInfo.mWifiModel){
            case "MASTER"://热点只需要这两个数据
                content=getResources().getString(R.string.hotspot);
                addToConfigFileDetailBeans(title,content);

                title="WIFI频段";
                content=deviceInfo.wifiInfo.mWifiBand;
                addToConfigFileDetailBeans(title,content);
                return;
            case "CLIENT":
                content=getResources().getString(R.string.wifi_hotspot);
                break;
            case "WDS_WIFI":
                content=getResources().getString(R.string.central_node_wifi);
                break;
            case "WDS_4G":
                content=getResources().getString(R.string.central_node_4G);
                break;
            case "WDS":
                content=getResources().getString(R.string.child_node);
                break;
        }
        addToConfigFileDetailBeans(title,content);

        title="SSID";
        content=deviceInfo.wifiInfo.mSsid;
        addToConfigFileDetailBeans(title,content);


        title="SSID密码";
        content=deviceInfo.wifiInfo.mPassword;
        addToConfigFileDetailBeans(title,content);


        title="自动获取IP";
        if(deviceInfo.wifiInfo.mDHCP){
            content="是";
            addToConfigFileDetailBeans(title,content);

        }else{
            content="否";
            addToConfigFileDetailBeans(title,content);


            title="IP地址";
            content=deviceInfo.wifiInfo.mIpAdress;
            addToConfigFileDetailBeans(title,content);

            title="子网前缀长度";
            content=deviceInfo.wifiInfo.mSubnetLength;
            addToConfigFileDetailBeans(title,content);

            title="默认网关";
            content=deviceInfo.wifiInfo.mDefaultGateway;
            addToConfigFileDetailBeans(title,content);

            title="DNS域名1";
            content=deviceInfo.wifiInfo.mDns1;
            addToConfigFileDetailBeans(title,content);

            title="DNS域名2";
            content=deviceInfo.wifiInfo.mDns2;
            addToConfigFileDetailBeans(title,content);
        }

        title="WIFI频段";
        content=deviceInfo.wifiInfo.mWifiBand;
        addToConfigFileDetailBeans(title,content);


    }

    private void addToConfigFileDetailBeans(String title,String content) {
        configFileDetailBean=new ConfigFileDetailBean();
        configFileDetailBean.setTitle(title);
        configFileDetailBean.setContent(content);
        configFileDetailBeans.add(configFileDetailBean);
    }

    private void showGprsData() {
        String apn;
        String apnName = "";
        if(deviceInfo.gprsInfo.mIsStartNet){
            title="启用GPRS设置";
            content="启用";
            addToConfigFileDetailBeans(title,content);

            apn=deviceInfo.gprsInfo.mApn;
            if(apn!=null){
                switch (apn) {
                    case "CMNET":
                        apnName = getString(R.string.china_mobile);
                        break;
                    case "3GNET":
                        apnName = getString(R.string.china_unicom);
                        break;
                    case "":
                        if(deviceInfo.gprsInfo.mApnUser.equals(getString(R.string.china_telecom_apn_user)) && deviceInfo.gprsInfo.mApnPass.equals(getString(R.string.china_telecom_apn_pass))){
                            apnName = getString(R.string.china_telecom);
                        }else{
                            apnName = getString(R.string.china_other);
                        }
                        break;
                    default:
                        apnName = getString(R.string.china_other);
                        break;
                }
            }
            title="运营商";
            content=apnName;
            addToConfigFileDetailBeans(title,content);


            title="APN用户名";
            content=deviceInfo.gprsInfo.mApnUser;
            addToConfigFileDetailBeans(title,content);


            title="APN密码";
            content=deviceInfo.gprsInfo.mApnPass;
            addToConfigFileDetailBeans(title,content);


            title="启用短信呼唤";
            if(deviceInfo.gprsInfo.mIsStartMessage){
                content="启用";
            }else{
                content="未启用";
            }
            addToConfigFileDetailBeans(title,content);


        }else{
            title="启用GPRS设置";
            content="未启用";
            addToConfigFileDetailBeans(title,content);

        }
    }


    public static ConfigFileDetailFragment newInstance(Bundle bundle) {
        ConfigFileDetailFragment fragment = new ConfigFileDetailFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    //当Activity与fragment建立关联时调用
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context=context;
    }

    @Override
    public void onClick(View v) {
        if(v==ivCommonBack){
            backTo();
        }
    }

    //目前这里只是为了实现eventbus
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void haveNull(NullEvent event) {
    }

    @Override
    protected void createPresenter(List<BasePresenter> mPresenters) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.layout_fragment_config_file_detail;
    }

    @Override
    protected void initView(View view) {
        ivCommonBack=view.findViewById(R.id.iv_common_back);
        tvCommonTitle=view.findViewById(R.id.tv_common_title);
        myListView=view.findViewById(R.id.myListview);
    }

    @Override
    protected void initListener(View view) {
        ivCommonBack.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        tvCommonTitle.setText(R.string.title_file_detail);
        myHandler =new MyHandler(this);
        deviceInfo= CommandParseManage.getInstance().getDeviceInfo();
        configFileDetailBeans=new ArrayList<>();
        Bundle bundle=getArguments();
        if(bundle!=null){
            fileName=bundle.getString(FILENAME);
            if(fileName!=null) {
                if(!fileName.equals("")){
                    new Thread(){
                        @Override
                        public void run() {
                            readDataFromFile(fileName);
                        }
                    }.start();
                }else{
                    Toast.makeText(context,"文件读取失败！",Toast.LENGTH_SHORT).show();
                }
            }else{
                Toast.makeText(context,"文件读取失败！",Toast.LENGTH_SHORT).show();
            }
        }else{
            Toast.makeText(context,"文件读取失败！",Toast.LENGTH_SHORT).show();
        }

        adapter=new ConfigFileDetailAdapter(configFileDetailBeans,context);
        myListView.setAdapter(adapter);
    }


    public void readDataFromFile(String fileName){
        String filePath= Environment.getExternalStorageDirectory()+"/"+fileName;
        File file =new File(filePath);
        if (!file.isFile() && !file.exists()) {
            return ;
        }
        InputStreamReader inputReader = null;
        BufferedReader buffreader = null;
        InputStream instream=null;
        try {
            instream = new FileInputStream(file);
            inputReader= new InputStreamReader(instream);
            buffreader = new BufferedReader(inputReader);
            String line;
            //分行读取
            while (( line = buffreader.readLine()) != null) {
                mCommandParseManage.parseCommaneLine(line);
                if(line.startsWith("@GNSS,GETALL,OK")){//表示完成了读取
                    myHandler.sendEmptyMessage(MSG_READ_SUCC);
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(inputReader!=null){
                    inputReader.close();
                }
                if(buffreader!=null){
                    buffreader.close();
                }
                if(instream!=null){
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
